<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1" isELIgnored="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Poke Messenger</title>

<link rel=stylesheet type="text/css"
	href="css/jquery-ui-1.8.17.custom.css" />
<style type="text/css">
.chat-panel {
	width: 300px;
	height: 250px;
	top: 0;
	position: fixed;
	left: 400px;
	top: 100px;
	display: block;
	font-size: small;
}

.chat-panel input {
	width: 100%;
	height: 25px;
	position: absolute;
	left: 0;
	bottom: 0;
}

.chat-panel-header {
	width: 100%;
	height: 25px;
	position: absolute;
	left: 0;
	height: 25px;
}

.chat-panel-content {
	position: absolute;
	top: 27px;
	bottom: 30px;
	left: 0;
	width: 100%;
}

.scrollable {
	overflow: scroll;
}

.chat-panel-titlebar-close {
	position: absolute;
	right: .3em;
}

.chat-panel-header-title {
	float: left;
	margin: 3px;
}

#room-list {
	border: thin;
}
</style>

<script type="text/javascript"
	src="javascript/jQuery/jquery-1.7.1.min.js"></script>
<script type="text/javascript"
	src="javascript/jQuery/jquery-ui-1.8.17.custom.min.js"></script>
<script type="text/javascript" src="/_ah/channel/jsapi"></script>

<script type="text/javascript">
	function loadRoomList() {
		$.ajax({
			url : "/service",
			data : {
				"action" : "getRoomList"
			},
			success : function(data) {
				var result = eval(data);
				console.log(result);
				$('#room-list > ul').html('');
				$.each(result.rooms, function(index, element) {
					var row = document.createElement('li');
					var link = document.createElement('a');
					link.href = "#" + element.key;
					link.innerHTML = element.name;

					$(link).click(function() {
						openChatRoom(element.key, element.name);
					});
					$(row).append(link);
					$('#room-list > ul').append(row);
				});
			}
		});
	}

	function loadContactList() {
		$.ajax({
			url : "/service",
			data : {
				"action" : "getContactList"
			},
			success : function(data) {
				var result = eval(data);
				console.log(result);
				$('#contact-list > ul').html('');
				$.each(result.contacts, function(index, element) {
					var row = document.createElement('li');
					var link = document.createElement('a');
					link.href = '#' + element.key;
					link.innerHTML = element.friendName;

					$(link).click(function() {
						openChatRoom(element.roomKey, element.friendName);
					});

					$(row).addClass('contact-item');
					$(row).draggable({
						zIndex: 1000000,
						revert : true,
						helper : "clone"
					});

					$(row).append(link);
					$('#contact-list > ul').append(row);
				});
			}
		});
	}

	function replyInvitation(key, decision) {
		$.ajax({
			url : "/service",
			data : {
				"action" : "reply",
				"invitation" : key,
				"accept" : (decision) ? "yes" : "no",
			},
			success : function() {
				if (decision)
					loadRoomList();
				loadInvitationList();
			}
		})
	}

	function openInvitation(invitation) {
		$('#dialog-invitation').html(
				invitation.sender + ' has invited you to room '
						+ invitation.room);

		$('#dialog-invitation').dialog({
			height : 140,
			modal : true,
			buttons : {
				"Yes" : function() {
					$(this).dialog('close');
					replyInvitation(invitation.key, true);
				},
				"No" : function() {
					$(this).dialog('close');
					replyInvitation(invitation.key, false);
				}
			}
		});
	}

	function loadInvitationList() {
		$.ajax({
			url : "/service",
			data : {
				"action" : "invitationList"
			},
			success : function(data) {
				var result = eval(data);
				$('#invitation-list > ul').html('');
				$.each(result.invitations, function(index, element) {
					var row = document.createElement('li');
					var link = document.createElement('a');
					link.href = '#' + element.key;
					link.innerHTML = element.sender + '#' + element.room;

					$(link).click(function() {
						openInvitation(element);
					});

					$(row).addClass('invitation-item');

					$(row).append(link);
					$('#invitation-list > ul').append(row);
				})
			}
		})
	}

	function onChannelMessage(message) {
		var result = $.parseJSON(message.data);

		if (result.type == "gotMessage") {
			updatePassive(result.roomKey, result.roomHeader);
			//updateChatPanel(result.roomKey);
		} else if (result.type == "gotFriend") {
			loadContactList();
		} else if (result.type == "gotInvitation") {
			loadInvitationList();
		}
	}

	function openChannel(data) {
		channel = new goog.appengine.Channel(data.token);
		socket = channel.open();
		//socket.onopen = onOpened;
		socket.onmessage = onChannelMessage;
		//socket.onerror = onError;
		//socket.onclose = onClose;
	}

	function getChannelToken() {
		$.ajax({
			url : "/service",
			data : {
				"action" : "getChannelToken"
			},
			success : function(data) {
				var result = eval(data);
				openChannel(result);
			}
		});
	}

	function checkLoginStatus() {
		$
				.ajax({
					url : "/service",
					data : {
						"action" : "checkLoginStatus"
					},
					success : function(data) {
						var result = eval(data);
						console.log(result);

						if (result.loggedin) {
							var curUser = result.user;
							// do sth here
							$('#user-panel')
									.html(
											'Welcome, '
													+ curUser.nickname
													+ '<br />'
													+ '<a href="' + result.logoutURL + '">Sign out</a>');

							loadRoomList();
							$('#create-room').button().click(function() {
								$('#dialog-create-room').dialog({
									height : 200,
									modal : true,
									buttons : {
										"Create" : function() {
											createRoom();
										}
									}
								});
							});
							loadContactList();
							$('#add-friend').button().click(function() {
								$('#dialog-invite-friend').dialog({
									height : 200,
									modal : true,
									buttons : {
										"Invite" : function() {
											inviteFriend();
										}
									}
								});
							});
							loadInvitationList();

							getChannelToken();
						} else {
							showLoginDialog(result.loginURL);
						}
					}
				});
	}

	function createRoom() {
		var formData = {
			"action" : "createRoom"
		};
		$('#create-room-form input').each(function(index, element) {
			formData[element.name] = element.value;
		});
		$.ajax({
			url : "/service",
			data : formData,
			success : function(data) {
				var result = eval(data);
				if (result.status == "ok") {
					$('#simple-dialog').html('Create room successfully');
					$('#simple-dialog').dialog({
						modal : true,
						buttons : {
							Ok : function() {
								$(this).dialog('close');
								$('#dialog-create-room').dialog('close');
							}
						}
					});
					loadRoomList();
				}
			}
		});
	}

	function inviteFriend() {
		var formData = {
			"action" : "inviteFriend"
		};
		$('#invite-friend-form input').each(function(index, element) {
			formData[element.name] = element.value;
		});
		$.ajax({
			url : "/service",
			data : formData,
			success : function(data) {
				var result = eval(data);
				if (result.status == "ok") {
					$('#simple-dialog').html('Invitation Sent');
					$('#simple-dialog').dialog({
						modal : true,
						buttons : {
							Ok : function() {
								$(this).dialog('close');
								$('#dialog-invite-friend').dialog('close');
							}
						}
					});
				}
			}
		});
	}

	function showLoginDialog(loginURL) {
		$('#dialog-login').html('Please <a href="' + loginURL +'">sign in</a>');
		$('#dialog-login').dialog({
			height : 150,
			modal : true,
			beforeClose : function() {
				return false
			},
		});
	}

	function getToTop(panel) {
		/* var count = 0;
		var max = 0;
		$('#chat-panel-zone .chat-panel').each(function(index, element) {
			if ($(element != panel))
				if (max < parseInt($(element).css('z-index')))
					max = parseInt($(element).css('z-index'));
		});
		panel.css('z-index', max + 1); */
		var tmp = parseInt(panel.css('z-index'));
		var max = $('#chat-panel-zone .chat-panel').length;
		$('#chat-panel-zone .chat-panel').each(function(index, element) {
			if ($(element) != panel) {
				var temp = parseInt($(element).css('z-index'))
				if (tmp < temp)
					$(element).css('z-index', temp - 1);
			}
		});
		panel.css('z-index', max);
	}

	function onMessageSend(event) {
		var key = event.data.key;
		var chatInput = $('#chat-panel-' + key).find('input[name=chatInput]');
		var message = chatInput.val();
		chatInput.val('');
		sendMessage(key, message);
		return false;
	}

	function updatePassive(key, header) {
		openChatRoom(key, header);

		var panel = $('#chat-panel-' + key);
		var from = panel.find('input[name=lastMessageAt]').val();
		if (from == "")
			getMessage(key);
		else
			getMessage(key, from);
	}

	function updateChatPanel(key) {
		var panel = $('#chat-panel-' + key);
		if (panel.length) {
			var from = panel.find('input[name=lastMessageAt]').val();
			//panel.show();
			if (from == "")
				getMessage(key);
			else
				getMessage(key, from);
		} else {
			var header = $('#room-list a[href=#' + key + ']').html();
			openChatRoom(key, header);
		}
	}

	function sendMessage(key, message) {
		$.ajax({
			url : "/service",
			data : {
				"action" : "sendMessage",
				"roomKey" : key,
				"message" : message
			},
			success : function(data) {
				var result = eval(data);
				updateChatPanel(key);
			}
		});
	}

	function getMessage(key, from) {
		$.ajax({
			url : "/service",
			data : {
				"action" : "getMessage",
				"roomKey" : key,
				"from" : from
			},
			success : function(data) {
				var result = eval(data);
				loadMessage(key, result);
			}
		});
	}

	function addFriendToRoom(friend, roomKey) {
		$.ajax({
			url : "/service",
			data : {
				"action" : "invite",
				"friend" : friend.find('a').attr('href').substring(1),
				"room" : roomKey,
			},
			success : function(data) {
				// alert result out
				alert("Invitation sent");
			}
		});
	}

	function createChatPanel(key, header) {
		var panel = $($('#chat-panel-root').clone().attr('id',
				'chat-panel-' + key));
		panel.find('.chat-panel-header .chat-panel-header-title').html(header);
		panel.click(function() {
			getToTop($(this))
		});
		panel.find('form').submit({
			"key" : key,
		}, onMessageSend);

		panel.find('.chat-panel-titlebar-close').button().click(function() {
			panel.hide();
		});

		$('#chat-panel-zone').append(panel);
		panel.draggable({
			handle : '.chat-panel-header'
		});
		panel.resizable();
		panel.droppable({
			greedy : true,
			accept : ".contact-item",
			hoverClass : "ui-state-highlight",
			activeClass : "ui-state-hover",
			drop : function(event, ui) {
				//alert("Dropped");
				// Add to room here
				var user = ui.draggable;
				addFriendToRoom(user, key);
			}
		});
		panel.css('display', 'block');
		panel.css('z-index', 1);
		getToTop(panel);
	}

	function openChatRoom(key, header) {
		if ($('#chat-panel-' + key).length) {
			var panel = $('#chat-panel-' + key);
			getToTop(panel);
			panel.show().effect("shake");
			panel.find('input[name=chatInput]').focus();
		} else {
			createChatPanel(key, header);
			getMessage(key);
		}
	}

	function loadMessage(key, data) {
		var panel = $('#chat-panel-' + key);
		$.each(data.messages, function(item, element) {
			if (!panel.find('.chat-line[name=' + element.id + ']').length) {
				var line = $('#chat-panel-root .chat-line').clone().html(
						element.sender + ":" + element.content).attr('name',
						element.id);
				panel.find('.chat-panel-content').append(line);
				panel.find('input[name=lastMessageAt]').val(element.timestamp);
			}
		});
		var chatContainer = panel.find('.chat-panel-content');
		chatContainer.scrollTop(chatContainer[0].scrollHeight);
	}

	// boot up everything here
	$(document).ready(function() {
		checkLoginStatus();
	});
</script>

</head>
<body>
	<div id="simple-dialog"></div>
	<div id="dialog-login"></div>

	<div id="user-panel" class="ui-widget"></div>
	<div id="room-list" class="ui-widget">
		<ul>
		</ul>
	</div>
	<button id="create-room">Create new chat room</button>

	<div id="contact-list" class="ui-widget">
		<ul>
		</ul>
	</div>
	<button id="add-friend">Add new friend</button>

	<div id="invitation-list" class="ui-widget">
		<ul>
		</ul>
	</div>

	<div id="dialog-invitation" title="Invitation" style="display: none">

	</div>

	<div id="dialog-create-room" title="Create new chat room"
		style="display: none">
		<form id="create-room-form" onsubmit="createRoom();return false;">
			<fieldset>
				<label for="name">Name: </label> <input type="text" name="roomName"
					class="text ui-widget-content ui-corner-all" />
			</fieldset>
		</form>
	</div>

	<div id="dialog-invite-friend" title="Invite your friend"
		style="display: none">
		<form id="invite-friend-form" onsubmit="inviteFriend();return false;">
			<fieldset>
				<label for="email">Email: </label> <input type="text" name="email"
					class="text ui-widget-content ui-corner-all" />
			</fieldset>
		</form>
	</div>

	<div id="chat-panel-zone"></div>
	<div id="chat-panel-root" class="chat-panel ui-widget ui-corner-all"
		style="display: none">
		<form>
			<div class="chat-panel-header ui-widget-header">
				<span class="chat-panel-header-title"></span> <a
					class="chat-panel-titlebar-close"><span
					class="ui-icon ui-icon-closethick">close</span> </a>
			</div>
			<div class="chat-panel-content ui-widget-content scrollable">
				<div class="chat-line ui-corner-all ui-widget"></div>

			</div>
			<input type="text" name="chatInput"
				class="text ui-widget-content ui-corner-all" /> <input
				type="hidden" name="lastMessageAt" />
		</form>
	</div>
</body>
</html>